using MES_workbench.ErrorCode;
using Microsoft.AspNetCore.Mvc;
using WebApplication1.Implement.DTO;
using WebApplication1.Implement.IServices;

namespace WebApplication1.Controllers
{
    /// <summary>
    /// 智能客服控制器
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class ChatController : ControllerBase
    {
        private readonly IChatService _chatService;
        private readonly ILogger<ChatController> _logger;

        /// <summary>
        /// 构造函数注入服务与日志
        /// </summary>
        public ChatController(IChatService chatService, ILogger<ChatController> logger)
        {
            _chatService = chatService;
            _logger = logger;
        }

        /// <summary>
        /// 发送消息给智能客服
        /// </summary>
        /// <param name="request">聊天消息请求</param>
        /// <returns>AI回复</returns>
        [HttpPost("message")]
        [ProducesResponseType(typeof(ApiResult<ChatMessageResponseDto>), StatusCodes.Status200OK)]
        public async Task<ActionResult<ApiResult<ChatMessageResponseDto>>> SendMessage([FromBody] ChatMessageRequestDto request)
        {
            _logger.LogInformation("[POST] /api/chat/message 调用，消息: {Message}", request.Message);
            
            if (!ModelState.IsValid)
            {
                var errors = ModelState.Values.SelectMany(v => v.Errors).Select(e => e.ErrorMessage);
                return BadRequest(new ApiResult<ChatMessageResponseDto> { msg = string.Join(", ", errors) });
            }

            var result = await _chatService.SendMessageAsync(request);
            return Ok(result);
        }

        /// <summary>
        /// 获取聊天历史记录
        /// </summary>
        /// <param name="sessionId">会话ID</param>
        /// <returns>聊天历史列表</returns>
        [HttpGet("history/{sessionId}")]
        [ProducesResponseType(typeof(ApiResult<List<ChatHistoryDto>>), StatusCodes.Status200OK)]
        public async Task<ActionResult<ApiResult<List<ChatHistoryDto>>>> GetChatHistory(string sessionId)
        {
            _logger.LogInformation("[GET] /api/chat/history/{SessionId} 调用", sessionId);
            var result = await _chatService.GetChatHistoryAsync(sessionId);
            return Ok(result);
        }

        /// <summary>
        /// 创建新的聊天会话
        /// </summary>
        /// <param name="userId">用户ID（可选）</param>
        /// <returns>会话ID</returns>
        [HttpPost("session")]
        [ProducesResponseType(typeof(ApiResult<string>), StatusCodes.Status200OK)]
        public async Task<ActionResult<ApiResult<string>>> CreateSession([FromQuery] string? userId = null)
        {
            _logger.LogInformation("[POST] /api/chat/session 调用，用户ID: {UserId}", userId);
            var result = await _chatService.CreateChatSessionAsync(userId);
            return Ok(result);
        }

        /// <summary>
        /// 获取用户的所有聊天会话
        /// </summary>
        /// <param name="userId">用户ID（可选）</param>
        /// <returns>会话列表</returns>
        [HttpGet("sessions")]
        [ProducesResponseType(typeof(ApiResult<List<ChatHistoryDto>>), StatusCodes.Status200OK)]
        public async Task<ActionResult<ApiResult<List<ChatHistoryDto>>>> GetUserSessions([FromQuery] string? userId = null)
        {
            _logger.LogInformation("[GET] /api/chat/sessions 调用，用户ID: {UserId}", userId);
            var result = await _chatService.GetUserSessionsAsync(userId);
            return Ok(result);
        }

        /// <summary>
        /// 智能客服健康检查
        /// </summary>
        /// <returns>服务状态</returns>
        [HttpGet("health")]
        [ProducesResponseType(typeof(ApiResult<object>), StatusCodes.Status200OK)]
        public ActionResult<ApiResult<object>> HealthCheck()
        {
            _logger.LogInformation("[GET] /api/chat/health 调用");
            
            var healthInfo = new
            {
                Status = "运行中",
                Timestamp = DateTime.Now,
                Service = "智能客服",
                Version = "1.0.0"
            };

            var result = new ApiResult<object>();
            result.success(healthInfo, "智能客服服务正常运行");
            return Ok(result);
        }
    }
}
